import { Card, message } from 'antd';
import ProForm, {
  ProFormDateRangePicker,
  ProFormDependency,
  ProFormDigit,
  ProFormRadio,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-form';
import { PageContainer } from '@ant-design/pro-layout';
import api from '@/services/ant-design-pro/api';
import { useIntl, FormattedMessage } from 'umi';


async function digestPassword(data) {
  const hash = await crypto.subtle.digest('SHA-1', new TextEncoder().encode(data));
  const hashArray = Array.from(new Uint8Array(hash));                     // convert buffer to byte array
  const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join(''); // convert bytes to hex string
  console.log(hashHex)
  return hashHex
}


const Setting = () => {
  const intl = useIntl();
  const onFinish = async (values) => {
    console.log(values)
    try {
      const { _, response } = await api.alterPwd(await digestPassword(values.pwd), await digestPassword(values.new_pwd), {
        getResponse: true,
      })
      if (response.status == 200) {
        message.success('success');
        return
      }
    } catch (error) {
      let status = error.response.status;
      let defaultLoginFailureMessage;
      if (status === 403) {
        defaultLoginFailureMessage = intl.formatMessage({
          id: 'pages.login.accountLogin.errorMessage',
          defaultMessage: '密码错误！',
        });
      } else {
        defaultLoginFailureMessage = 'fail';
      }
      message.error(defaultLoginFailureMessage)
    }
  };

  return (
    <Card bordered={false}>
      <ProForm
        hideRequiredMark
        style={{
          margin: 'auto',
          marginTop: 8,
          maxWidth: 600,
        }}
        name="basic"
        layout="vertical"
        initialValues={{
          public: '1',
        }}
        onFinish={onFinish}
      >
        <ProFormText.Password
          width="md"
          label="旧密码"
          name="pwd"
          rules={[
            {
              required: true,
              message: '请输入旧密码',
            },
          ]}
        />

        <ProFormText.Password
          width="md"
          label="新密码"
          name="new_pwd"
          rules={[
            {
              required: true,
              message: '请输入新密码',
            },
          ]}
        />

      </ProForm>
    </Card>
  );
};

export default Setting;
